/*
 * @Description: 页面标题操作组件
 * @Author: Rfan
 * @Date: 2022-09-19 14:08:51
 * @LastEditTime: 2022-09-19 17:48:40
 */

import { useState } from 'react';
import { Button, Empty, Progress, Upload } from 'antd';
import cs from 'classnames';
import classNames from 'classnames/bind';
import { debounce } from 'lodash';
import { HddTwoTone, UploadOutlined } from '@ant-design/icons';
import { useOnlinePreviewContext } from '../contexts/OnlinePreviewContext';
import styles from '../styles/pageUpload.module.scss';
import { uploadResource } from '@/api/upload';

const cx = classNames.bind(styles);

const UploadPage = (props: any) => {
  const { classname } = props;
  const { parsingEEPFunc } = useOnlinePreviewContext();

  // 选中文件列表
  const [uploadList, setUploadList] = useState([]);
  // 上传文件按钮loading状态
  const [uploadLoading, setUploadLoading] = useState(false);
  // 上传进度
  const [uploadPercent, setUploadPercent] = useState(0);

  /**
   * @description: upload组件上传前钩子，处理选中的文件列表
   * @param {File} file
   */
  const beforeUpload = (file: File) => {
    setUploadList((state) => [...state, file]);
    return true;
  };

  const getFileUrl = (name: string, fileUrls: any): string => {
    return fileUrls.find((item: any) => item.name === name)?.url || '';
  };

  /**
   * @description: 上传选中的文件
   * @param {File[]} fileList
   */
  const uploadFileFunc = (fileList: File[]): void => {
    setUploadLoading(true);
    const formData = new FormData();
    fileList.forEach((file: File) => {
      formData.append('files', file);
    });

    uploadResource(formData, {
      timeout: 0,
      onUploadProgress: (progress: any) => {
        setUploadPercent(Number(((progress.loaded / progress.total) * 100).toFixed(1)));
      }
    }).then((res: any) => {
      const fileUrlObjs = res.data;
      const fileUrl = getFileUrl(fileUrlObjs[0]?.name, fileUrlObjs);
      parsingEEPFunc({ fileUrl }).finally(() => {
        // setUploadLoading(false);
      });
    });
  };

  return (
    <div className={cs('page-operate', classname, cx('page-upload'))}>
      <Empty
        image={<HddTwoTone />}
        imageStyle={{
          fontSize: 60
        }}
        description="点击上传需预览的EEP文件"
      >
        <Upload
          beforeUpload={beforeUpload}
          maxCount={1}
          fileList={[]}
          customRequest={debounce(() => {
            setUploadLoading(false);
            uploadFileFunc(uploadList);
          })}
        >
          <Button
            type="primary"
            size="large"
            loading={uploadLoading}
            icon={<UploadOutlined />}
            onClick={() => {
              setUploadList([]);
              setUploadPercent(0);
            }}
          >
            上传
          </Button>
        </Upload>
        <div style={{ marginTop: '24px', width: 300, height: 32 }}>
          {uploadPercent > 0 && (
            <Progress
              strokeColor={{
                '0%': '#108ee9',
                '100%': '#87d068'
              }}
              percent={uploadPercent}
              status={uploadPercent === 100 ? 'success' : 'active'}
            />
          )}
        </div>
      </Empty>
    </div>
  );
};

export default UploadPage;
